package com.luwanglin.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luwanglin.eduservice.entity.EduChapter;
import com.luwanglin.eduservice.entity.EduVideo;
import com.luwanglin.eduservice.entity.chapter.ChapterVo;
import com.luwanglin.eduservice.entity.chapter.VideoVo;
import com.luwanglin.eduservice.mapper.EduChapterMapper;
import com.luwanglin.eduservice.service.EduChapterService;
import com.luwanglin.eduservice.service.EduVideoService;
import com.luwanglin.commonutils.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-05-13
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    final
    EduVideoService eduVideoService;

    public EduChapterServiceImpl(EduVideoService eduVideoService) {
        this.eduVideoService = eduVideoService;
    }

    @Override
    public List<ChapterVo> getChapterAndVideo(String courseId) {
        QueryWrapper<EduChapter> wrapperChapter = new QueryWrapper<>();
        wrapperChapter.eq("course_id", courseId);
        List<EduChapter> eduChapters = baseMapper.selectList(wrapperChapter);

        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id", courseId);
        List<EduVideo> eduVideos = eduVideoService.list(wrapperVideo);
        List<ChapterVo> chapterVos = new ArrayList<>();
        for (EduChapter eduChapter : eduChapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter, chapterVo);
            chapterVos.add(chapterVo);
            for (EduVideo eduVideo : eduVideos) {
                if (eduVideo.getChapterId().equals(eduChapter.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo, videoVo);
                    chapterVo.getChildren().add(videoVo);
                }

            }
        }

        return chapterVos;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        int count = eduVideoService.count(new QueryWrapper<EduVideo>().eq("chapter_id", chapterId));
        if (count > 0) {
            throw new GuliException(20001, "cant not delete ,video must be empty");
        } else {
            int delete = baseMapper.deleteById(chapterId);
            return delete > 0;
        }

    }

    @Override
    public boolean removeByCourseId(String courseId) {
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        int count = baseMapper.delete(queryWrapper);
        return count > 0;
    }
}
